package model;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;

import javax.swing.JTextField;

@SuppressWarnings("serial")
public class DecimalTextField extends JTextField {

	private DecimalFormat df;

	public DecimalTextField() {
		super();
		this.setHorizontalAlignment(JTextField.RIGHT);
		df = new DecimalFormat();
		df.applyPattern("#,##0.00; -#,##0.00");
		applyActions();
	}

	private void applyActions() {

		this.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent evt) {
				if (evt.getKeyCode() == KeyEvent.VK_ENTER)
					transferFocus();
			}
		});

		this.addFocusListener(new FocusAdapter() {
			public void focusLost(FocusEvent evt) {
				Float floatvalor = Float.parseFloat(getText().replace(".", "")
						.replace(",", "."));
				setText(df.format(floatvalor));
			}
		});

		this.addFocusListener(new FocusAdapter() {
			public void focusGained(FocusEvent evt) {
				selectAll();
			}
		});
	}

	public void setValue(Float valor) {
		this.setText(df.format(valor));
	}

	public float getFloatValue() {
		return Float.parseFloat(getText().replace(".", "").replace(",", "."));
	}

}
